package com.system.travel.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.system.travel.common.utils.StringUtils;
import com.system.travel.modules.system.entity.SysPermission;
import com.system.travel.modules.system.entity.SysRole;
import com.system.travel.modules.system.entity.SysUser;
import com.system.travel.modules.system.mapper.SysUserMapper;
import com.system.travel.modules.system.mapper.SysRoleMapper;
import com.system.travel.modules.system.mapper.SysPermissionMapper;
import com.system.travel.modules.system.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPermissionMapper permissionMapper;

    @Override
    public SysUser getByUsername(String username) {
        return userMapper.selectOne(
            new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)
                .eq(SysUser::getDelFlag, 0)
        );
    }

    @Override
    public Map<String, Object> getUserInfo(Long userId) {
        // 获取用户基本信息
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("userId", user.getId());
        data.put("username", user.getUsername());
        data.put("nickname", user.getNickname());
        data.put("avatar", user.getAvatar());

        // 获取角色列表
        List<String> roles = roleMapper.selectRolesByUserId(userId)
            .stream()
            .map(SysRole::getRoleCode)
            .collect(Collectors.toList());

        // 获取权限列表
        List<Map<String, Object>> permissions = permissionMapper.selectPermissionsByUserId(userId)
            .stream()
            .map(p -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", p.getId());
                map.put("parentId", p.getParentId());
                map.put("name", p.getName());
                map.put("permission", p.getPermission());
                map.put("type", p.getType());
                map.put("path", p.getUrl());
                map.put("component", p.getComponent());
                map.put("icon", p.getIcon());
                map.put("sort", p.getSort());
                map.put("visible", p.getVisible());
                map.put("status", p.getStatus());
                return map;
            })
            .collect(Collectors.toList());

        data.put("roles", roles);
        data.put("permissions", permissions);

        return data;
    }
} 